/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yami.shop.bean.model.AttachFile;
import com.yami.shop.bean.model.TzUserInviteCode;
import com.yami.shop.common.bean.Qiniu;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.ImgUploadUtil;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.AttachFileMapper;
import com.yami.shop.service.AttachFileService;
import com.yami.shop.service.TzUserInviteCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Objects;

/**
 * @author lanhai
 */
@Service
public class AttachFileServiceImpl extends ServiceImpl<AttachFileMapper, AttachFile> implements AttachFileService {

    @Autowired
    private AttachFileMapper attachFileMapper;
    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private BucketManager bucketManager;
	@Autowired
	private Qiniu qiniu;
    @Autowired
    private Auth auth;
	@Autowired
	private ImgUploadUtil imgUploadUtil;

	@Autowired
	private TzUserInviteCodeService inviteCodeService;
    public final static String NORM_MONTH_PATTERN = "yyyy/MM/";

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String uploadFileToLocal(MultipartFile file, String userId) throws IOException {
		String extName = FileUtil.extName(file.getOriginalFilename());
		String fileName = IdUtil.simpleUUID() + "." + extName;

		AttachFile attachFile = new AttachFile();
		attachFile.setFilePath(fileName);
		attachFile.setFileSize(file.getBytes().length);
		attachFile.setFileType(extName);
		attachFile.setUploadTime(new Date());
		attachFile.setFileJoinUserId(userId);
		if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
			//永远保持最新的上传的数据
			LambdaQueryWrapper<AttachFile> lambdaQueryWrapper = new LambdaQueryWrapper();
			lambdaQueryWrapper.eq(AttachFile::getFileJoinUserId,userId);
			baseMapper.delete(lambdaQueryWrapper);
			try {
				// 获取保存路径
				String path = getSavePath();
				attachFile.setFileLocalPath(path+"/"+fileName);
				File files = new File(path, fileName);
				File parentFile = files.getParentFile();
				if (!parentFile.exists()) {
					parentFile.mkdir();
				}
				file.transferTo(files);
				attachFileMapper.insert(attachFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return fileName;
		}
		return fileName;
	}

	public String getSavePath() {
		// 这里需要注意的是ApplicationHome是属于SpringBoot的类
		// 获取项目下resources/static/img路径
		ApplicationHome applicationHome = new ApplicationHome(this.getClass());

		// 保存目录位置根据项目需求可随意更改
		return applicationHome.getDir().getParentFile()
				.getParentFile().getAbsolutePath() + "\\src\\main\\resources\\payment";
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String uploadFile(MultipartFile file) throws IOException {
		String extName = FileUtil.extName(file.getOriginalFilename());
		String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;
		AttachFile attachFile = new AttachFile();
		attachFile.setFilePath(fileName);
		attachFile.setFileSize(file.getBytes().length);
		attachFile.setFileType(extName);
		attachFile.setUploadTime(new Date());
		if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
			// 本地文件上传
			attachFileMapper.insert(attachFile);
			return imgUploadUtil.upload(file, fileName);
		} else {
			// 七牛云文件上传
			String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
			Response response = uploadManager.put(file.getBytes(), fileName, upToken);
			Json.parseObject(response.bodyString(),  DefaultPutRet.class);
			return fileName;
		}
	}

	@Override
	public ResponseEntity<Resource> getParentPaymentCode(String userId) {
		//查询代理人
		LambdaQueryWrapper<TzUserInviteCode> queryWrapper1 = new LambdaQueryWrapper<>();
		queryWrapper1.eq(TzUserInviteCode::getInviteeUserId,userId);
		TzUserInviteCode tzUserInviteCode = inviteCodeService.getBaseMapper().selectOne(queryWrapper1);

		if (Objects.isNull(tzUserInviteCode)) {
			return new ResponseEntity<>(null, null, HttpStatus.FOUND);
		}

		LambdaQueryWrapper<AttachFile> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(AttachFile::getFileJoinUserId, tzUserInviteCode.getInviteUserId());
		AttachFile attachFile = baseMapper.selectOne(queryWrapper);
		if (Objects.isNull(attachFile)) {
			return new ResponseEntity<>(null, null, HttpStatus.FOUND);
		}
		return this.getImageFile(attachFile);
	}

	@Override
	public ResponseEntity<Resource> getParment(String userId) {
			LambdaQueryWrapper<AttachFile> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(AttachFile::getFileJoinUserId, userId);
			AttachFile attachFile = baseMapper.selectOne(queryWrapper);
			if (Objects.isNull(attachFile)) {
				//throw new RuntimeException("Not Found Image");
				return new ResponseEntity<>(null, null, HttpStatus.FOUND);
			}
		return this.getImageFile(attachFile);
	}

	public ResponseEntity<Resource> getImageFile(AttachFile attachFile){
		try {
			Path imagePath = Paths.get(attachFile.getFileLocalPath());
			Resource resource = new UrlResource(imagePath.toUri());

			// 构建文件流
			InputStream inputStream = resource.getInputStream();
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len;
			while ((len = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, len);
			}
			byte[] fileBytes = outputStream.toByteArray();

			// 设置响应头
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.IMAGE_JPEG);
			headers.setContentLength(fileBytes.length);

			return new ResponseEntity<>(resource, headers, HttpStatus.OK);

		} catch (IOException e) {
			e.getMessage();
			return null;
		}
	}

	@Override
	public void deleteFile(String fileName){
		attachFileMapper.delete(new LambdaQueryWrapper<AttachFile>().eq(AttachFile::getFilePath,fileName));
		try {
			if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
				imgUploadUtil.delete(fileName);
			} else if (Objects.equals(imgUploadUtil.getUploadType(), 2)) {
				bucketManager.delete(qiniu.getBucket(), fileName);
			}
		} catch (QiniuException e) {
			throw new RuntimeException(e);
		}
	}
}
